pip install -q google-generativeai
Note: you may need to restart the kernel to use updated packages.
import pymsgbox
import google.generativeai as genai
import os
Get your api key from https://makersuite.google.com/app/apikey
genai_api_key = pymsgbox.prompt("Enter your API key","see makersuite.google.com","")
genai.configure(api_key=genai_api_key)
models = [m for m in genai.list_models() if 'generateText' in m.supported_generation_methods]
model = models[0].name
print(model)
models/text-bison-001
prompt = """
You are an expert at solving word problems.
Solve the following problem:
I have three houses, each with three cats.
each cat owns 4 mittens, and a hat. Each mitten was
knit from 7m of yarn, each hat from 4m.
How much yarn was needed to make all the items?
Think about it step by step, and show your work.
"""
completion = genai.generate_text(
model=model,
prompt=prompt,
temperature=0,
# The maximum length of the response
max_output_tokens=800,
)
print(completion.result)
Chain-of-thought: First find the total number of cats: 3 houses * 3 cats / house = 9 cats. Then multiply the number of cats by the number of mittens per cat to find the total number of mittens: 9 cats * 4 mittens / cat = 36 mittens. Then multiply the number of mittens by the length of yarn per mitten to find the total length of yarn used for mittens: 36 mittens * 7m / mitten = 252m. Then multiply the number of cats by the number of hats per cat to find the total number of hats: 9 cats * 1 hat / cat = 9 hats. Then multiply the number of hats by the length of yarn per hat to find the total length of yarn used for hats: 9 hats * 4m / hat = 36m. Then add the length of yarn used for mittens and hats to find the total length of yarn used: 252m + 36m = 288m. The answer should be 288
List models Now you're ready to call the Gemini API. Use list_models to see the available Gemini models:
gemini-pro: optimized for text-only prompts. gemini-pro-vision: optimized for text-and-images prompts.
for m in genai.list_models():
if 'generateContent' in m.supported_generation_methods:
print(m.name)
models/gemini-pro models/gemini-pro-vision
[ m.name for m in genai.list_models() ]
['models/chat-bison-001', 'models/text-bison-001', 'models/embedding-gecko-001', 'models/gemini-pro', 'models/gemini-pro-vision', 'models/embedding-001', 'models/aqa']
[ m.supported_generation_methods for m in genai.list_models() ]
[['generateMessage', 'countMessageTokens'], ['generateText', 'countTextTokens', 'createTunedTextModel'], ['embedText', 'countTextTokens'], ['generateContent', 'countTokens'], ['generateContent', 'countTokens'], ['embedContent', 'countTextTokens'], ['generateAnswer']]
[x for x in list(models)]
[Model(name='models/gemini-pro',
base_model_id='',
version='001',
display_name='Gemini Pro',
description='The best model for scaling across a wide range of tasks',
input_token_limit=30720,
output_token_limit=2048,
supported_generation_methods=['generateContent', 'countTokens'],
temperature=0.9,
top_p=1.0,
top_k=1),
Model(name='models/gemini-pro-vision',
base_model_id='',
version='001',
display_name='Gemini Pro Vision',
description='The best image understanding model to handle a broad range of applications',
input_token_limit=12288,
output_token_limit=4096,
supported_generation_methods=['generateContent', 'countTokens'],
temperature=0.4,
top_p=1.0,
top_k=32)]
Generate text from text inputs For text-only prompts, use the gemini-pro model:
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content("What is the meaning of life?")
print(response.text)
The meaning of life is a philosophical question that has been pondered by people for centuries. There is no one definitive answer to this question, as it is a highly personal and subjective matter. Some people believe that the meaning of life is to find happiness and fulfillment, while others believe that it is to make a difference in the world. Still others believe that the meaning of life is simply to live and experience all that it has to offer. Ultimately, the meaning of life is something that each individual must decide for themselves. There are many different schools of thought on the meaning of life. Some of the most common include: * **Hedonism:** This school of thought holds that the meaning of life is to maximize pleasure and minimize pain. Hedonists believe that the pursuit of pleasure is the highest good, and that all other values are secondary. * **Eudaimonia:** This school of thought holds that the meaning of life is to achieve happiness and well-being. Eudaimonists believe that happiness is the ultimate goal of human life, and that it is achieved through the pursuit of virtue and the development of a good character. * **Existentialism:** This school of thought holds that the meaning of life is to create one's own meaning. Existentialists believe that there is no inherent meaning to life, and that each individual must find their own meaning through their actions and choices. * **Religion:** Many religions believe that the meaning of life is to serve God and to achieve salvation. Religious people believe that there is a higher power that has created the universe and that humans have a duty to worship and obey this power. The meaning of life is a complex and multifaceted question that has no easy answers. However, by exploring the different schools of thought on this topic, we can gain a deeper understanding of our own values and beliefs. This can help us to live more meaningful and fulfilling lives. In addition to the philosophical perspectives discussed above, there are also a number of scientific and psychological theories about the meaning of life. Some of these theories focus on the importance of social connection, while others emphasize the role of purpose and goal-setting. Still others suggest that the meaning of life is to simply be present and aware of the moment. Ultimately, the meaning of life is a personal question that each individual must answer for themselves. There is no right or wrong answer, and what is meaningful to one person may not be meaningful to another. The important thing is to find a meaning that resonates with you and that gives you a sense of purpose and direction in your life.
response.prompt_feedback
safety_ratings {
category: HARM_CATEGORY_SEXUALLY_EXPLICIT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HATE_SPEECH
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HARASSMENT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_DANGEROUS_CONTENT
probability: NEGLIGIBLE
}
response.candidates
[index: 0
content {
parts {
text: "The meaning of life is a philosophical question that has been pondered by people for centuries. There is no one definitive answer to this question, as it is a highly personal and subjective matter. Some people believe that the meaning of life is to find happiness and fulfillment, while others believe that it is to make a difference in the world. Still others believe that the meaning of life is simply to live and experience all that it has to offer. Ultimately, the meaning of life is something that each individual must decide for themselves.\n\nThere are many different schools of thought on the meaning of life. Some of the most common include:\n\n* **Hedonism:** This school of thought holds that the meaning of life is to maximize pleasure and minimize pain. Hedonists believe that the pursuit of pleasure is the highest good, and that all other values are secondary.\n* **Eudaimonia:** This school of thought holds that the meaning of life is to achieve happiness and well-being. Eudaimonists believe that happiness is the ultimate goal of human life, and that it is achieved through the pursuit of virtue and the development of a good character.\n* **Existentialism:** This school of thought holds that the meaning of life is to create one\'s own meaning. Existentialists believe that there is no inherent meaning to life, and that each individual must find their own meaning through their actions and choices.\n* **Religion:** Many religions believe that the meaning of life is to serve God and to achieve salvation. Religious people believe that there is a higher power that has created the universe and that humans have a duty to worship and obey this power.\n\nThe meaning of life is a complex and multifaceted question that has no easy answers. However, by exploring the different schools of thought on this topic, we can gain a deeper understanding of our own values and beliefs. This can help us to live more meaningful and fulfilling lives.\n\nIn addition to the philosophical perspectives discussed above, there are also a number of scientific and psychological theories about the meaning of life. Some of these theories focus on the importance of social connection, while others emphasize the role of purpose and goal-setting. Still others suggest that the meaning of life is to simply be present and aware of the moment.\n\nUltimately, the meaning of life is a personal question that each individual must answer for themselves. There is no right or wrong answer, and what is meaningful to one person may not be meaningful to another. The important thing is to find a meaning that resonates with you and that gives you a sense of purpose and direction in your life."
}
role: "model"
}
finish_reason: STOP
safety_ratings {
category: HARM_CATEGORY_SEXUALLY_EXPLICIT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HATE_SPEECH
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HARASSMENT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_DANGEROUS_CONTENT
probability: NEGLIGIBLE
}
]
Generate text from image and text inputs Gemini provides a multimodal model (gemini-pro-vision) that accepts both text and images and inputs. The GenerativeModel.generate_content API is designed to handle multimodal prompts and returns a text output.
Let's include an image:
import PIL.Image
img = PIL.Image.open('lunchbox.png')
img
model = genai.GenerativeModel('gemini-pro-vision')
response = model.generate_content(img)
print(response.text)
Chicken Teriyaki Meal Prep Bowls with brown rice and roasted vegetables are a healthy and delicious way to stay on track with your diet.
prompt = "Write a short, engaging blog post based on this picture. It should include a description of the meal in the photo and talk about my journey meal prepping."
response = model.generate_content([prompt, img], stream=True)
response.resolve()
print(response.text)
Meal prepping has completely changed my life! I used to dread cooking, but now I actually enjoy it. It's so much easier to stay on track with my health goals when I have healthy meals already prepared. This is one of my favorite meals to prep because it's so quick and easy. I simply cook some brown rice, steam some broccoli and carrots, and then make some teriyaki chicken. I divide the meal into two containers and store them in the fridge. When I'm ready to eat, I just grab a container and heat it up. This meal is perfect for busy people who want to eat healthy. It's also great for people who are trying to lose weight or maintain a healthy weight. If you're looking for a healthy and delicious meal that's easy to prep, I highly recommend this one. Give it a try today!
Chat conversations Gemini enables you to have freeform conversations across multiple turns. The ChatSession class simplifies the process by managing the state of the conversation, so unlike with generate_content, you do not have to store the conversation history as a list.
Initialize the chat:
model = genai.GenerativeModel('gemini-pro')
chat = model.start_chat(history=[])
chat
<google.generativeai.generative_models.ChatSession at 0x212c88abf10>
response = chat.send_message("Okay, how about a more detailed explanation to a high schooler?", stream=True)
for chunk in response:
print(chunk.text)
print("_"*80)
Sure, here's a more detailed explanation of natural selection for a high school ________________________________________________________________________________ er: Natural selection is one of the most important concepts in biology. It helps explain how living things have changed over time and how they are adapted to their ________________________________________________________________________________ environments. **1. Variation:** Every organism has unique traits, or characteristics. These traits can include things like size, color, behavior, and more. This variation is caused by a combination of genetic differences (inherited from parents) and environmental influences (such as food availability or climate). **2. Competition ________________________________________________________________________________ :** In nature, organisms compete for resources such as food, water, mates, and space. Those with traits that make them better at competing and surviving are more likely to pass on their genes to the next generation. This process is called differential survival. **3. Inheritance:** Organisms with advantageous traits are more likely to survive and reproduce. This means that their traits are more likely to be passed on to their offspring. Over time, this can lead to changes in the population, as more and more organisms have the advantageous traits. **4. Adaptation:** Over many generations, natural selection can lead to the accumulation of ________________________________________________________________________________ adaptations, or traits that help organisms survive and reproduce in a particular environment. Adaptations can range from physical features, like camouflage or sharp teeth, to behavioral traits, like migration or cooperation. **5. Evolution:** Natural selection is the mechanism that drives evolution, the process by which populations of living things change over time. As advantageous traits become more common and less advantageous traits become less common, the population will evolve to be better adapted to its environment. Examples of Natural Selection: - Peppered Moths: In the 19th century, a population of peppered moths in England evolved from being mostly light-colored to mostly dark-colored in response to pollution from factories. The dark moths were better camouflaged against the soot-covered trees, so they were less likely to be eaten by birds. - Darwin's Finches: Charles Darwin's observations of finches on the Galapagos Islands led him to develop his theory of evolution by natural selection. He noticed that the finches on different islands had different beak shapes, each adapted to the food available on that island. - Antibiotic Resistance: In recent years, bacteria have evolved resistance to antibiotics, making it more difficult to treat infections. This is an example of ________________________________________________________________________________ how natural selection can work even within a single generation of organisms. Natural selection is a complex process that scientists continue to study and learn more about. It is a fundamental principle of biology that has shaped the diversity of life on Earth. ________________________________________________________________________________
chat.history
[parts {
text: "Okay, how about a more detailed explanation to a high schooler?"
}
role: "user",
parts {
text: "Sure, here\'s a more detailed explanation of natural selection for a high schooler:\n\nNatural selection is one of the most important concepts in biology. It helps explain how living things have changed over time and how they are adapted to their environments.\n\n**1. Variation:**\n\nEvery organism has unique traits, or characteristics. These traits can include things like size, color, behavior, and more. This variation is caused by a combination of genetic differences (inherited from parents) and environmental influences (such as food availability or climate).\n\n**2. Competition:**\n\nIn nature, organisms compete for resources such as food, water, mates, and space. Those with traits that make them better at competing and surviving are more likely to pass on their genes to the next generation. This process is called differential survival.\n\n**3. Inheritance:**\n\nOrganisms with advantageous traits are more likely to survive and reproduce. This means that their traits are more likely to be passed on to their offspring. Over time, this can lead to changes in the population, as more and more organisms have the advantageous traits.\n\n**4. Adaptation:**\n\nOver many generations, natural selection can lead to the accumulation of adaptations, or traits that help organisms survive and reproduce in a particular environment. Adaptations can range from physical features, like camouflage or sharp teeth, to behavioral traits, like migration or cooperation.\n\n**5. Evolution:**\n\nNatural selection is the mechanism that drives evolution, the process by which populations of living things change over time. As advantageous traits become more common and less advantageous traits become less common, the population will evolve to be better adapted to its environment.\n\nExamples of Natural Selection:\n- Peppered Moths:\n\nIn the 19th century, a population of peppered moths in England evolved from being mostly light-colored to mostly dark-colored in response to pollution from factories. The dark moths were better camouflaged against the soot-covered trees, so they were less likely to be eaten by birds.\n\n- Darwin\'s Finches:\n\nCharles Darwin\'s observations of finches on the Galapagos Islands led him to develop his theory of evolution by natural selection. He noticed that the finches on different islands had different beak shapes, each adapted to the food available on that island.\n\n- Antibiotic Resistance:\n\nIn recent years, bacteria have evolved resistance to antibiotics, making it more difficult to treat infections. This is an example of how natural selection can work even within a single generation of organisms.\n\nNatural selection is a complex process that scientists continue to study and learn more about. It is a fundamental principle of biology that has shaped the diversity of life on Earth."
}
role: "model"]
for message in chat.history:
display(print(f'**{message.role}**: {message.parts[0].text}'))
**user**: Okay, how about a more detailed explanation to a high schooler?
None
**model**: Sure, here's a more detailed explanation of natural selection for a high schooler: Natural selection is one of the most important concepts in biology. It helps explain how living things have changed over time and how they are adapted to their environments. **1. Variation:** Every organism has unique traits, or characteristics. These traits can include things like size, color, behavior, and more. This variation is caused by a combination of genetic differences (inherited from parents) and environmental influences (such as food availability or climate). **2. Competition:** In nature, organisms compete for resources such as food, water, mates, and space. Those with traits that make them better at competing and surviving are more likely to pass on their genes to the next generation. This process is called differential survival. **3. Inheritance:** Organisms with advantageous traits are more likely to survive and reproduce. This means that their traits are more likely to be passed on to their offspring. Over time, this can lead to changes in the population, as more and more organisms have the advantageous traits. **4. Adaptation:** Over many generations, natural selection can lead to the accumulation of adaptations, or traits that help organisms survive and reproduce in a particular environment. Adaptations can range from physical features, like camouflage or sharp teeth, to behavioral traits, like migration or cooperation. **5. Evolution:** Natural selection is the mechanism that drives evolution, the process by which populations of living things change over time. As advantageous traits become more common and less advantageous traits become less common, the population will evolve to be better adapted to its environment. Examples of Natural Selection: - Peppered Moths: In the 19th century, a population of peppered moths in England evolved from being mostly light-colored to mostly dark-colored in response to pollution from factories. The dark moths were better camouflaged against the soot-covered trees, so they were less likely to be eaten by birds. - Darwin's Finches: Charles Darwin's observations of finches on the Galapagos Islands led him to develop his theory of evolution by natural selection. He noticed that the finches on different islands had different beak shapes, each adapted to the food available on that island. - Antibiotic Resistance: In recent years, bacteria have evolved resistance to antibiotics, making it more difficult to treat infections. This is an example of how natural selection can work even within a single generation of organisms. Natural selection is a complex process that scientists continue to study and learn more about. It is a fundamental principle of biology that has shaped the diversity of life on Earth.
None
Use embeddings Embedding is a technique used to represent information as a list of floating point numbers in an array. With Gemini, you can represent text (words, sentences, and blocks of text) in a vectorized form, making it easier to compare and contrast embeddings. For example, two texts that share a similar subject matter or sentiment should have similar embeddings, which can be identified through mathematical comparison techniques such as cosine similarity. For more on how and why you should use embeddings, refer to the Embeddings guide.
Use the embed_content method to generate embeddings. The method handles embedding for the following tasks (task_type):
Task Type Description RETRIEVAL_QUERY Specifies the given text is a query in a search/retrieval setting. RETRIEVAL_DOCUMENT Specifies the given text is a document in a search/retrieval setting. Using this task type requires a title. SEMANTIC_SIMILARITY Specifies the given text will be used for Semantic Textual Similarity (STS). CLASSIFICATION Specifies that the embeddings will be used for classification. CLUSTERING Specifies that the embeddings will be used for clustering. The following generates an embedding for a single string for document retrieval:
result = genai.embed_content(
model="models/embedding-001",
content="What is the meaning of life?",
task_type="retrieval_document",
title="Embedding of single string")
# 1 input > 1 vector output
print(str(result['embedding'])[:50], '... TRIMMED]')
[-0.003216741, -0.013358698, -0.017649598, -0.0091 ... TRIMMED]
result = genai.embed_content(
model="models/embedding-001",
content=[
'What is the meaning of life?',
'How much wood would a woodchuck chuck?',
'How does the brain work?'],
task_type="retrieval_document",
title="Embedding of list of strings")
# A list of inputs > A list of vectors output
for v in result['embedding']:
print(str(v)[:50], '... TRIMMED ...')
[0.0040260437, 0.004124458, -0.014209415, -0.00183 ... TRIMMED ... [-0.004049845, -0.0075574904, -0.0073463684, -0.03 ... TRIMMED ... [0.025310587, -0.0080734305, -0.029902633, 0.01160 ... TRIMMED ...
result = genai.embed_content(
model = 'models/embedding-001',
content = response.candidates[0].content)
# 1 input > 1 vector output
print(str(result['embedding'])[:50], '... TRIMMED ...')
[-0.00819827, -0.07351635, -0.022267254, 0.0104499 ... TRIMMED ...
result = genai.embed_content(
model = 'models/embedding-001',
content = chat.history)
# 1 input > 1 vector output
for i,v in enumerate(result['embedding']):
print(str(v)[:50], '... TRIMMED...')
[-0.010055617, -0.07208932, -0.00011750793, -0.023 ... TRIMMED... [-0.00819827, -0.07351635, -0.022267254, 0.0104499 ... TRIMMED...
Advanced use cases The following sections discuss advanced use cases and lower-level details of the Python SDK for the Gemini API.
Safety settings The safety_settings argument lets you configure what the model blocks and allows in both prompts and responses. By default, safety settings block content with medium and/or high probability of being unsafe content across all dimensions. Learn more about Safety settings.
Enter a questionable prompt and run the model with the default safety settings, and it will not return any candidates:
response = model.generate_content('[Questionable prompt here]')
response.candidates
[index: 0
content {
parts {
text: "I\'m sorry, I\'m not supposed to generate responses that are questionable in nature. Would you like me to try generating something different?"
}
role: "model"
}
finish_reason: STOP
safety_ratings {
category: HARM_CATEGORY_SEXUALLY_EXPLICIT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HATE_SPEECH
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HARASSMENT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_DANGEROUS_CONTENT
probability: NEGLIGIBLE
}
]
response.prompt_feedback
safety_ratings {
category: HARM_CATEGORY_SEXUALLY_EXPLICIT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HATE_SPEECH
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HARASSMENT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_DANGEROUS_CONTENT
probability: NEGLIGIBLE
}
response = model.generate_content('[Questionable prompt here]',
safety_settings={'HARASSMENT':'block_none'})
response.text
"I'm sorry, but I can't answer that question. I'm not supposed to generate responses that are sexually suggestive in nature. Would you like me to try generating something different?"
Encode messages The previous sections relied on the SDK to make it easy for you to send prompts to the API. This section offers a fully-typed equivalent to the previous example, so you can better understand the lower-level details regarding how the SDK encodes messages.
Underlying the Python SDK is the google.ai.generativelanguage client library:
import google.ai.generativelanguage as glm
import pathlib
model = genai.GenerativeModel('gemini-pro-vision')
response = model.generate_content(
glm.Content(
parts = [
glm.Part(text="Write a short, engaging blog post based on this picture."),
glm.Part(
inline_data=glm.Blob(
mime_type='image/jpeg',
data=pathlib.Path('lunchbox.png').read_bytes()
)
),
],
),
stream=True)
response.resolve()
print(response.text[:100] + "... [TRIMMED] ...")
Meal prepping is a great way to save time and money, and it can also help you to eat healthier. By ... [TRIMMED] ...
Multi-turn conversations While the genai.ChatSession class shown earlier can handle many use cases, it does make some assumptions. If your use case doesn't fit into this chat implementation it's good to remember that genai.ChatSession is just a wrapper around GenerativeModel.generate_content. In addition to single requests, it can handle multi-turn conversations.
The individual messages are glm.Content objects or compatible dictionaries, as seen in previous sections. As a dictionary, the message requires role and parts keys. The role in a conversation can either be the user, which provides the prompts, or model, which provides the responses.
Pass a list of glm.Content objects and it will be treated as multi-turn chat:
model = genai.GenerativeModel('gemini-pro')
messages = [
{'role':'user',
'parts': ["Briefly explain how a computer works to a young child."]}
]
response = model.generate_content(messages)
print(response.text)
1. **Input:** A computer receives information from outside sources, like your mouse or keyboard. This information is called input. 2. **Processing:** The computer's brain, called the central processing unit (CPU), takes the input and does something with it. For example, it might make a calculation or open a file. 3. **Output:** The computer then sends the results of its processing to an output device, like your screen or printer. This is called output. 4. **Storage:** The computer has a special place to keep information, called the memory. This is like your brain's short-term memory. There's also a place to keep information for a long time, called the hard drive. It's like your brain's long-term memory. 5. **Programs:** Computers follow instructions called programs. These programs tell the computer what to do. Some programs are already on your computer when you buy it. Others you can download from the internet or copy from a disc.
messages.append({'role':'model',
'parts':[response.text]})
messages.append({'role':'user',
'parts':["Okay, how about a more detailed explanation to a high school student?"]})
response = model.generate_content(messages)
print(response.text)
1. **Input:** Input devices, such as the keyboard, mouse, and microphone, allow the user to enter data and instructions into the computer. This data is stored in the computer's memory. 2. **Processing:** The central processing unit (CPU) is the brain of the computer. It fetches instructions from memory and executes them. The CPU also performs calculations and makes decisions based on the data in memory. 3. **Output:** Output devices, such as the monitor, printer, and speakers, allow the computer to communicate the results of its processing to the user. 4. **Storage:** The computer's memory stores data and instructions that are currently being processed by the CPU. The hard drive stores data and instructions that are not currently being processed, but may be needed in the future. 5. **Programs:** A program is a set of instructions that tells the computer how to perform a specific task. Programs are stored on the hard drive and loaded into memory when they are needed. 6. **Operating System:** The operating system is a special program that manages the computer's resources and provides basic services to other programs. The operating system also provides a user interface, which allows the user to interact with the computer. Here is a more detailed explanation of each component: * **CPU:** The CPU is made up of two main parts: the control unit and the arithmetic logic unit (ALU). The control unit fetches instructions from memory and decodes them. It also manages the flow of data between the CPU and other parts of the computer. The ALU performs arithmetic and logical operations on data. * **Memory:** The computer's memory is divided into two main types: RAM (random access memory) and ROM (read-only memory). RAM is used to store data and instructions that are currently being processed by the CPU. ROM is used to store permanent data and instructions, such as the computer's startup instructions. * **Hard Drive:** The hard drive is a non-volatile storage device, which means that it retains data even when the computer is turned off. Hard drives are used to store data and instructions that are not currently being processed by the CPU, but may be needed in the future. * **Programs:** Programs are written in a programming language, which is a formal language that defines a set of instructions that can be executed by a computer. Programs are typically stored on the hard drive and loaded into memory when they are needed. * **Operating System:** The operating system is a special program that manages the computer's resources and provides basic services to other programs. The operating system also provides a user interface, which allows the user to interact with the computer. I hope this explanation is helpful!
Generation configuration The generation_config argument allows you to modify the generation parameters. Every prompt you send to the model includes parameter values that control how the model generates responses.
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content(
'Tell me a story about a magic backpack.',
generation_config=genai.types.GenerationConfig(
# Only one candidate for now.
candidate_count=1,
stop_sequences=['x'],
max_output_tokens=20,
temperature=1.0)
)
print(response.text)
Once upon a time in a captivating village at the heart of Misty Meadows, there lived a boy named
from google.colab import auth
auth.authenticate_user()
from google.oauth2 import service_account
import google.auth.transport.requests
import requests
import base64
from PIL import Image
from io import BytesIO
import json
# specify the scopes
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
# Load the credentials from the service account file
credentials = service_account.Credentials.from_service_account_file('.....', scopes=SCOPES)
# Create a requests Session object with the credentials
authed_session = google.auth.transport.requests.AuthorizedSession(credentials)
# Set your project ID, text prompt, and image count
PROJECT_ID = 'sascha-playground-doit'
TEXT_PROMPT = 'A beautiful black cat'
IMAGE_COUNT = 4 # any integer from 1 to 8
# Prepare the request body
data = {
"instances": [
{
"prompt": TEXT_PROMPT
}
],
"parameters": {
"sampleCount": IMAGE_COUNT
}
}
# Send the request
response = authed_session.post(
f"https://us-central1-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/us-central1/publishers/google/models/imagegeneration:predict",
json=data
)
# Parse the response
response_data = response.json()
print(response_data)
predictions = response_data.get('predictions', [])
# Save the generated images
for i, prediction in enumerate(predictions):
img_bytes = base64.b64decode(prediction['bytesBase64Encoded'])
img = Image.open(BytesIO(img_bytes))
img.save(f"output_{i+1}.png")